package org.asiainfo.gateway.handler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.asiainfo.common.core.domain.R;
import org.asiainfo.gateway.form.CaptchaTrackBody;
import org.asiainfo.gateway.service.IValidateCodeService;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyExtractors;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 验证码获取、校验
 *
 * @author dotor-ww
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ValidateCodeHandler {

    private final IValidateCodeService validateCodeService;

    /**
     * 获取验证码状态
     *
     * @param serverRequest 请求
     * @return 结果
     */
    public Mono<ServerResponse> getCaptchaStatus(ServerRequest serverRequest) {
        R<Object> data = validateCodeService.getCaptchaStatus(serverRequest);
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(data));
    }

    /**
     * 生成验证码
     *
     * @param serverRequest 请求
     * @return 结果
     */
    public Mono<ServerResponse> createCaptcha(ServerRequest serverRequest) {
        R<Object> data = validateCodeService.createCaptcha(serverRequest);
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(data));
    }

    /**
     * 校验验证码
     *
     * @param serverRequest 请求
     * @return 结果
     */
    public Mono<ServerResponse> checkCaptcha(ServerRequest serverRequest) {
        // 获取请求体
        Mono<CaptchaTrackBody> requestBodyMono = serverRequest.body(BodyExtractors.toMono(CaptchaTrackBody.class));
        return requestBodyMono.flatMap(requestBody -> {
            R<Object> data = validateCodeService.checkCaptcha(serverRequest, requestBody);
            return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(data));
        });
    }
}
